import { createRouter, createWebHistory } from "vue-router";

// 动态导入路由组件
const modules = import.meta.glob("../views/**/*.vue");
// console.log('modules', modules)

// 动态导入路由配置
const configs: TObj = import.meta.glob("../views/**/*pageConfig.ts", {
	eager: true,
});
// console.log('configs', configs)

// 存储生成的路由配置
const routeMap: TObj = {};

// 将导入的组件转换为路由配置
Object.keys(modules).forEach((key) => {
	// 获取路由配置文件的路径
	const pathParts = key.split("/");
	pathParts.pop(); // Remove the .vue file part
	const configPath = pathParts.join("/") + "/pageConfig.ts";

	// 获取对应的路由配置
	const config = configs[configPath]?.routeConfig;
	// 不存在 || 隐藏的路由 跳过
	if (!config || config.hide) return;

	// 构造路由对象
	const route = {
		path: config.path,
		name: config.name,
		icon: config.icon,
		component: modules[key], // 懒加载组件
	};

	if (config.parentPath) {
		// 如果有父级路由
		if (!routeMap[config.parentPath]) {
			routeMap[config.parentPath] = {
				path: config.parentPath,
				name: config.parentName,
				icon: config.icon,
				children: [],
			};
		}
		routeMap[config.parentPath].children.push(route);
	} else {
		// 顶级路由
		routeMap[config.path] = route;
	}
});

// 生成路由数组
const routes = Object.values(routeMap).map((route) => {
	if (route.children && route.children.length === 0) {
		delete route.children;
	}
	return route;
});

console.log("routes", routes);

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes: [
		...routes,
		// {
		// 	path: "/",
		// 	name: "日报",
		// 	component: () => import("../views/Daily/DailyView.vue"),
		// },
		// {
		//   path: '/about',
		//   name: 'about',
		//   // route level code-splitting
		//   // this generates a separate chunk (About.[hash].js) for this route
		//   // which is lazy-loaded when the route is visited.
		//   component: () => import('../views/AboutView.vue')
		// }
	],
});

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
	console.log("to", to);

	if (
		routes.some(
			(route) =>
				route.path === to.path ||
				route.children?.some((child: TObj) => child.path === to.path)
		)
	) {
		next();
	} else if (to.path === "/") {
		next({ name: "日报" });
	} else {
		// 路由不在范围之内的 跳转到404
		next({ name: "NotFound" });
	}
});

export default router;
